package cn.webestar.scms.microsvc.controller;

import cn.webestar.scms.commons.Assert;
import cn.webestar.scms.commons.CommonException;
import cn.webestar.scms.commons.R;
import cn.webestar.scms.commons.api.*;
import cn.webestar.scms.commons.entity.BasicDO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.dao.UncategorizedDataAccessException;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author zgs
 */
public abstract class BaseController<T extends BasicDO<ID>, ID extends Serializable> {

    /**
     * 获取service
     */
    public abstract IService<T> getService();

    public R<T> _create(CreateBody body) {
        T o = body.toDO();
        getService().save(o);
        return R.success(o);
    }

    public R<Boolean> _delete(ID id) {
        Assert.notNull(id, 40001, "id不能为空");
        Boolean f = getService().removeById(id);
        return R.success(f);
    }

    public R<T> _update(UpdateBody body) {
        T o = body.toDO();
        getService().updateById(o);
        return R.success(o);
    }

    public R<T> _findById(ID id) {
        Assert.notNull(id, 40001, "id不能为空");
        T o = getService().getById(id);
        return R.success(o);
    }

    public R<Map<ID, T>> _findByIds(Set<ID> ids) {
        Assert.notNull(ids, 40001, "ids不能为空");
        Assert.isTrue(!ids.isEmpty(), 40002, "ids不能为空");
        List<T> list = getService().listByIds(ids);
        Map<ID, T> map = new HashMap<>(10);
        list.forEach((item) -> map.put(item.getId(), item));
        return R.success(map);
    }

    public R<PageVO<T>> _page(PageBody body) {
        Assert.notNull(body.getPageNum(), 40001, "pageNum不能为空");
        Assert.notNull(body.getPageSize(), 40002, "pageSize不能为空");
        Assert.isTrue(body.getPageSize() <= 200, 40003, "pageSize长度不能超过200");
        Page<T> p = new Page<>(body.getPageNum(), body.getPageSize(), true);
        IPage<T> page = getService().page(p, body.toQueryWapper());
        return R.success(new PageVO<>(page.getCurrent(), page.getSize(), page.getTotal(), page.getRecords()));
    }

    public R<T> _findOne(SimpleBody body) {
        T o = null;
        try {
            o = getService().getOne(body.toQueryWapper());
        } catch (UncategorizedDataAccessException e) {
            throw new CommonException(31001, e.getMessage());
        }
        // 解决无法转换null返回的问题
        return R.success(o);
    }

    public R<List<T>> _limitList(@RequestBody LimitBody body) {
        Assert.notNull(body.getOffset(), 40001, "offset不能为空");
        Assert.notNull(body.getLimit(), 40002, "limit不能为空");
        List<T> list = getService().list(body.toQueryWapper());
        return R.success(list);
    }

}
